<?php
namespace Console\Map;

use Commons\MobileControl\Car;
use Swoole\Process;
use Swoole\WebSocket\Frame;
use Swoole\WebSocket\Server AS WebSocketServer;

class Event
{
    public $events = [];
    /**
     * @var \Commons\MobileControl\Car
     */
    private $kulalaClient;

    public function __construct()
    {
    }

    public function dispatcher(WebSocketServer $server, Frame $frame, Process $process = null)
    {
        $frameId = $frame->fd;
        $message = $frame->data;
        $message = $message[0] == '{' ? json_decode($message) : $message;
        if (!is_object($message)) {
            return;
        }
        $method = $message->act;
        if (method_exists($this, $method)) {
            call_user_func_array([$this, $method], [$server, $frameId, $message->data, $process]);
        }
    }

    public function getCarStatus(WebSocketServer $server, $frameId, $data)
    {
        $result = $this->getKulalaCarRes(['carId' => '23685'], 'kulala.api.car.status.get');
        if (isset($result['result']['status']) && $result['result']['status'] == 1) {
            swoole_timer_tick(1000, function () use ($server, $frameId, $result)
            {
                $arr = explode(',', $result['carStatusInfo']['gps']);
                $server->push($frameId->fd, json_encode([
                    'act'      => 'query',
                    'location' => self::returnSquarePoint(103.9597346, 30.7532292)
                ]));
            });
        }
    }

    /**
     * 汽车控制
     *
     * @param WebSocketServer $server
     * @param                 $frameId
     * @param                 $data
     *
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function controlCar(WebSocketServer $server, $frameId, $data)
    {
        $instruct = $data->instruct;
        $carId    = $data->carId;
        if (is_numeric($instruct) && is_numeric($carId)) {
            $params = ['carId' => $carId, 'instruction' => $instruct];
            $result = $this->getKulalaCarRes($params, 'kulala.api.car.control');
            if (isset($result['result']['status']) && $result['result']['status'] == 1) {
                $server->push($frameId, json_encode([
                    'act' => 'control',
                    'msg' => '操作成功'
                ]));
            }
        }
    }

    /**
     * @param array  $params
     * @param string $method
     *
     * @return mixed|\Psr\Http\Message\ResponseInterface|\Psr\Http\Message\StreamInterface
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getKulalaCarRes(array $params, $method = '')
    {
        $this->kulalaClient = new Car();
        return $this->kulalaClient->query($params, $method);
    }

    public function json($data, $unescaped = true, $numericCheck = true)
    {
        if (is_array($data)) {
            if ($unescaped) {
                return $numericCheck ? json_encode($data, JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK) : json_encode($data, JSON_UNESCAPED_UNICODE);
            } else {
                return $numericCheck ? json_encode($data, JSON_NUMERIC_CHECK) : json_encode($data);
            }
        }
        return $data;
    }

    public function heartbeat(WebSocketServer $serv, $frameId)
    {
        if (ServerTask::isWebSocketClient($frameId, $serv)) {
            $serv->push($frameId, $this->json(['act' => '♥']));
        };
    }

}
